package server

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gofiber/fiber/v2"
	jwtware "github.com/gofiber/jwt/v2"

	"publish-manage/pkg/constant"
)

var Jwtware = jwtware.New(jwtware.Config{
	SigningKey:    []byte(constant.JWT_SECRET),
	ContextKey:    constant.JWT_CONTEXT,
	SigningMethod: "HS256",
	TokenLookup:   "header:Authorization,cookie:token",
	ErrorHandler: func(c *fiber.Ctx, err error) error {
		if err.Error() == "Missing or malformed JWT" {
			return c.Status(fiber.StatusBadRequest).SendString("无效的token信息")
		} else {
			return c.Status(fiber.StatusUnauthorized).SendString("Invalid or expired Authorization Token")
		}
	},
	SuccessHandler: func(c *fiber.Ctx) error {
		// 从jwt获取用户信息
		jwtToken := c.Locals(constant.JWT_CONTEXT).(*jwt.Token)
		claims := jwtToken.Claims.(jwt.MapClaims)
		uid := claims["uid"].(string)
		//sid := claims["sid"].(string)

		c.Locals("userId", uid)
		return c.Next()
	},
})
